package com.kim.pong.service;

import com.google.common.util.concurrent.RateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.UUID;

@Service
public class PongService {
    private Logger logger = LoggerFactory.getLogger(PongService.class);

    private RateLimiter rateLimiter;

    public PongService(){
        this.rateLimiter = RateLimiter.create(1.0);
    }
    public PongService(RateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }


    public Mono<ServerResponse> handlePing(ServerRequest request) {
        Mono<ServerResponse> resp;
        String trakingNumber = getTrackingNumber();
        logger.info(trakingNumber+ "request : " + request);
        if(rateLimiter.tryAcquire()){
            logger.info(trakingNumber+"try acquire success return ");
            resp = ServerResponse.ok()
                    .contentType(MediaType.TEXT_PLAIN)
                    .body(BodyInserters.fromValue("World"));
        }else {
            logger.info(trakingNumber+"stop by Throttling Control");
            resp = ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                    .contentType(MediaType.TEXT_PLAIN)
                    .body(BodyInserters.fromValue("Too many requests"));

        }
        return resp;

    }

    public String getTrackingNumber(){
        UUID uuid = UUID.randomUUID();
        return uuid + " - ";
    }
}
